package com.kyyc.luff.auth.config;

import com.kyyc.luff.auth.exception.LuffAccessDeniedHandler;
import com.kyyc.luff.auth.exception.ResourceAuthExceptionEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.servlet.http.HttpServletResponse;

/**
 * 资源访问权限配置
 * 给接口地址让security管理起来，如哪些不需要授权能访问，
 * 哪些需要登录授权后能访问，哪些需要用户拥有这些角色才能访问。
 **/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;
    @Autowired
    private LuffAccessDeniedHandler luffAccessDeniedHandler;


    private static final String[] PATTERN_URLS = {
            "/actuator/**",
            "/druid/**"
    };

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                //.authenticationEntryPoint(new UnauthorizedEntryPoint())
                .and()
                .authorizeRequests()
                .antMatchers(PATTERN_URLS).permitAll()
                .anyRequest().authenticated();
    }


    /**
     * 根据client_id设置资源id
     * 设置自定义授权异常信息
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        //String resourceIds = publicMapper.getResourceIdsByClientId(clientId);
        //设置客户端所能访问的资源id集合(默认取第一个是本服务的资源)
        //resources.resourceId(resourceIds.split(",")[0]).stateless(true);

        //自定义Token异常信息,用于token校验失败返回信息
        resources
                .tokenStore(tokenStore);

        resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint)
                .accessDeniedHandler(luffAccessDeniedHandler);
    }
}

